package com.lagou.zk;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {

    public static DataSource dataSource;

    //传参初始化DataSource
    public static void init(String mysqlconf) throws Exception {
        Properties p = new Properties();
        p.load(new StringReader(mysqlconf));
        dataSource = DruidDataSourceFactory.createDataSource(p);
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    //获取连接
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //测试数据库连接
    public static void mysqlTest() throws SQLException {
        String sql = "select * from info";

        Connection connection = DruidUtils.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()) {
            String information = resultSet.getString(1);
            System.out.println("数据库连接成功，查询结果：" + information);
            System.out.println("---------------------------------------------");
            System.out.println();
        }

        resultSet.close();
        ps.close();
        connection.close();
    }

    //配置文件被删除，datasource为空，连接池关闭
    public static void closeDruid(){
        dataSource = null;
    }
}
